import React, { useContext, Dispatch, useEffect } from 'react';

import { QueryContext } from '../../store';
import { resetJsonGroup } from '../../store/actions';
import { Config, Action, JsonRuleGroup, JsonPathGroup, JsonPathRule, JsonPathRuleGroup } from '../../types';
import styles from '../../styles.less';
import GroupConditions from '../group/GroupConditions';
import GroupActions from '../group/GroupActions';
import Rule from './Rule';
import RuleGroup from './RuleGroup';

const Group: React.FC<{
  config: Config,
  value?: JsonPathGroup,
}> = (props) => {
  const { config, value } = props;

  const { state, dispatch } = useContext<{state: JsonPathGroup, dispatch: Dispatch<Action>}>(QueryContext);

  useEffect(() => {
    if (value && value != state) {
      dispatch(resetJsonGroup(value))
    }
  }, [value])

  const renderActions = () => {
    return (
      <GroupActions
        config={config}
        path={state.path || ""}
        onClick={(action) => dispatch(action)}
      />
    );
  }

  const renderCondition = () => {
    return (
      <GroupConditions
        config={config}
        condition={state.condition}
        not={state.not}
        path={state.path || ""}
        onChange={(action) => dispatch(action)}
      />
    );
  }

  const renderHeader = () => {
    return (
      <div className={styles.groupheader}>
        {renderCondition()}
        {renderActions()}
      </div>
    );
  }

  const renderItem = () => {
    return state.rules?.map(rule => {
      if ((rule as JsonRuleGroup).condition) {
        return (
          <RuleGroup
            key={(rule as JsonPathRuleGroup).path||""}
            config={config}
            group={rule as JsonPathRuleGroup}
          />
        );
      } else {
        return (
          <Rule
            key={(rule as JsonPathRule).path||""}
            path={(rule as JsonPathRule).path||""}
            rule={rule as JsonPathRule}
            config={config}
          />
        );
      }
    });
  }

  return (
    <div className={styles.group}>
      {renderHeader()}
      {renderItem()}
    </div>
  );
}

export default Group;
